package xyz.ssf.cloud.common.core.storage;

import com.upyun.RestManager;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import xyz.ssf.cloud.common.config.StorageConfig;

import java.io.InputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 又拍云存储策略实现
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class UpYunStorageStrategy implements StorageStrategy {
    
    private final StorageConfig storageConfig;
    
    @Override
    public String uploadFile(MultipartFile file, String path, String filename) throws Exception {
        InputStream inputStream = file.getInputStream();
        return uploadFile(inputStream, path, filename);
    }
    
    @Override
    public String uploadFile(InputStream inputStream, String path, String filename) throws Exception {
        // 获取又拍云配置
        StorageConfig.UpYun upYunConfig = storageConfig.getUpyun();
        String bucketName = upYunConfig.getBucketName();
        String operatorName = upYunConfig.getOperatorName();
        String operatorPwd = upYunConfig.getOperatorPwd();
        String domain = upYunConfig.getDomain();
        
        log.info("准备上传文件到又拍云: path={}, filename={}", path, filename);
        log.info("检查又拍云配置: bucketName={}, operatorName={}, domain={}, 密码是否存在={}", 
              bucketName, 
              operatorName, 
              domain, 
              (operatorPwd != null && !operatorPwd.isEmpty()));
        
        if (operatorPwd == null) {
            log.error("又拍云操作员密码为 null，尝试从配置文件直接读取默认值");
            operatorPwd = "H9flrRQQvBnqMt0EdXUwc1RtJetLcnee"; // 临时使用配置文件中的默认值
        } else if (operatorPwd.isEmpty()) {
            log.error("又拍云操作员密码为空字符串，尝试从配置文件直接读取默认值");
            operatorPwd = "H9flrRQQvBnqMt0EdXUwc1RtJetLcnee"; // 临时使用配置文件中的默认值
        }
        
        if (!StringUtils.hasText(bucketName) || !StringUtils.hasText(operatorName) || 
            !StringUtils.hasText(operatorPwd) || !StringUtils.hasText(domain)) {
            throw new IllegalArgumentException("又拍云存储配置不完整");
        }
        
        // 创建又拍云客户端
        RestManager manager = new RestManager(bucketName, operatorName, operatorPwd);
        log.info("已创建又拍云客户端, bucketName={}", bucketName);
        
        // 构建存储路径
        if (!StringUtils.hasText(path)) {
            path = "";
        } else if (!path.endsWith("/")) {
            path = path + "/";
        }
        
        if (path.startsWith("/")) {
            path = path.substring(1);
        }
        
        String savePath = "/" + path + filename;
        log.info("又拍云存储路径: {}", savePath);
        
        // 上传参数
        Map<String, String> params = new HashMap<>();
        // 设置 MD5 校验
        // params.put(RestManager.PARAMS.CONTENT_MD5.getValue(), md5);
        // 设置访问密钥
        // params.put(RestManager.PARAMS.CONTENT_SECRET.getValue(), "secret");
        
        // 上传文件
        log.info("开始上传文件到又拍云: {}", savePath);
        okhttp3.Response okResponse = manager.writeFile(savePath, inputStream, params);
        Response response = convertToResponse(okResponse);
        log.info("又拍云上传响应码: {}", response.getResponseCode());
        
        if (response.isSuccessful()) {
            if (!domain.startsWith("http://") && !domain.startsWith("https://")) {
                domain = "https://" + domain;
            }
            
            if (!domain.endsWith("/")) {
                domain = domain + "/";
            }
            
            return domain + path + filename;
        } else {
            log.error("上传到又拍云失败: {} {}", response.getResponseCode(), response.getResponseMessage());
            throw new RuntimeException("上传到又拍云失败: " + response.getResponseCode() + " " + response.getResponseMessage());
        }
    }
    
    @Override
    public boolean deleteFile(String fileUrl) throws Exception {
        // 获取又拍云配置
        StorageConfig.UpYun upYunConfig = storageConfig.getUpyun();
        String bucketName = upYunConfig.getBucketName();
        String operatorName = upYunConfig.getOperatorName();
        String operatorPwd = upYunConfig.getOperatorPwd();
        String domain = upYunConfig.getDomain();
        
        log.info("准备从又拍云删除文件: fileUrl={}", fileUrl);
        log.info("检查又拍云配置: bucketName={}, operatorName={}, domain={}, 密码是否存在={}", 
              bucketName, 
              operatorName, 
              domain, 
              (operatorPwd != null && !operatorPwd.isEmpty()));
        
        if (operatorPwd == null) {
            log.error("又拍云操作员密码为 null，尝试从配置文件直接读取默认值");
            operatorPwd = "H9flrRQQvBnqMt0EdXUwc1RtJetLcnee"; // 临时使用配置文件中的默认值
        } else if (operatorPwd.isEmpty()) {
            log.error("又拍云操作员密码为空字符串，尝试从配置文件直接读取默认值");
            operatorPwd = "H9flrRQQvBnqMt0EdXUwc1RtJetLcnee"; // 临时使用配置文件中的默认值
        }
        
        if (!StringUtils.hasText(bucketName) || !StringUtils.hasText(operatorName) || 
            !StringUtils.hasText(operatorPwd) || !StringUtils.hasText(domain)) {
            throw new IllegalArgumentException("又拍云存储配置不完整");
        }
        
        // 创建又拍云客户端
        RestManager manager = new RestManager(bucketName, operatorName, operatorPwd);
        
        // 从URL中提取路径
        String filepath;
        
        if (!domain.startsWith("http://") && !domain.startsWith("https://")) {
            domain = "https://" + domain;
        }
        
        if (!domain.endsWith("/")) {
            domain = domain + "/";
        }
        
        if (fileUrl.startsWith(domain)) {
            filepath = fileUrl.substring(domain.length());
        } else {
            filepath = fileUrl;
        }
        
        if (!filepath.startsWith("/")) {
            filepath = "/" + filepath;
        }
        
        // 删除文件
        okhttp3.Response okResponse = manager.deleteFile(filepath, null);
        Response response = convertToResponse(okResponse);
        return response.isSuccessful();
    }
    
    /**
     * 将okhttp3.Response转换为自定义Response对象
     */
    private Response convertToResponse(okhttp3.Response okResponse) {
        try {
            boolean isSuccessful = okResponse.isSuccessful();
            int responseCode = okResponse.code();
            String responseMessage = okResponse.message();
            return new Response(isSuccessful, responseCode, responseMessage);
        } finally {
            // 确保关闭原始响应
            if (okResponse != null && okResponse.body() != null) {
                okResponse.close();
            }
        }
    }
    
    @Override
    public String getType() {
        return StorageType.UPYUN.getCode();
    }
    
    /**
     * 又拍云响应类
     */
    private static class Response {
        private final boolean isSuccessful;
        private final int responseCode;
        private final String responseMessage;
        
        public Response(boolean isSuccessful, int responseCode, String responseMessage) {
            this.isSuccessful = isSuccessful;
            this.responseCode = responseCode;
            this.responseMessage = responseMessage;
        }
        
        public boolean isSuccessful() {
            return isSuccessful;
        }
        
        public int getResponseCode() {
            return responseCode;
        }
        
        public String getResponseMessage() {
            return responseMessage;
        }
    }
} 